/* eslint-disable default-case */
import { message } from 'antd';
import {
  getDownloadInfo,
  getDownloadInfoSend,
  getDownloadInfoTax,
  getUploadProgress,
  uploadFileImport,
  uploadFileSend,
  uploadFileTax,
} from '@/services/salaybatchcs';
import * as service from '@/services/socket';
import { SocketActions, batchTaskFactory } from '@/models/socket';
import { delay } from '@/utils/dva';
// 非常重要属性
const namespace = 'salaybatchcs';
const ModelAddEmp = {
  namespace,
  state: {
    batchQuery: {
      // 批量上传数据
      progressPercent: 0,
      wageFalg: '2', // 导入类型	2、待发放。4、待报税、

      // 接单方待发放工资导入
      custId: undefined,
      custName: undefined,
      incmType: undefined,
      busiYm: undefined,
      wageDate: undefined,
      changeFlag: '2', // 是否变更发放日期
      wageReaSendDate: undefined,
      reaRsn: undefined,
    },
    custNameList: [],
    supplyList: [],
    isGoBack: false,
    currentStep: 0,
    progressPercent: 0,
    resultInfo: {
      // 结果数据必传
      batchName: '', // 任务名称
      taskCount: 0, // 导入数据
      successCount: 0, // 成功数据
      errorCount: 0, // 失败数据
      batchNo: '', // 批次号
      errorUrl: '/csApi/wageDowoload/dowoloadErrorExist', // 下载错误信息地址
      errorParams: null, // 下载错误数据参数
    },
    showProgress: false,
    batchTaskType: 'import',
  },
  effects: {
    // 获取下载模板fileId fileName
    *getDownloadInfo({ payload }, { call, put }) {
      const response = yield call(getDownloadInfo, payload);
      yield put({
        type: 'updateQuery',
        payload,
      });
      if (response.success) {
        const fileInfo = response.data.data.split('|');
        yield put({
          type: 'publicdata/setFileDownload',
          payload: { fileId: fileInfo[0], fileName: fileInfo[1] },
        });
      }
    },
    // 待发放获取下载模板fileId fileName
    *getDownloadInfoSend({ payload }, { call, put }) {
      const response = yield call(getDownloadInfoSend, payload);
      yield put({
        type: 'updateQuery',
        payload,
      });
      if (response.success) {
        const fileInfo = response.data.data.split('|');
        yield put({
          type: 'publicdata/setFileDownload',
          payload: { fileId: fileInfo[0], fileName: fileInfo[1] },
        });
      }
    },
    // 待报税获取下载模板fileId fileName
    *getDownloadInfoTax({ payload }, { call, put }) {
      const response = yield call(getDownloadInfoTax, payload);
      yield put({
        type: 'updateQuery',
        payload,
      });
      if (response.success) {
        const fileInfo = response.data.data.split('|');
        yield put({
          type: 'publicdata/setFileDownload',
          payload: { fileId: fileInfo[0], fileName: fileInfo[1] },
        });
      }
    },
    // 获取上传进度数据
    *getUploadProgress({ payload, callback }, { call, put }) {
      const response = yield call(getUploadProgress, payload);
      if (response.success) {
        yield put({
          type: 'updateQuery',
          payload: { progressPercent: response.data.successProp },
        });
      }
      if (callback && typeof callback === 'function') {
        callback(response);
      }
    },
    // 上传文件:批量进度
    uploadFileWithProgress:[
      function* ({ payload }, { call, put }) {
      try {
        let api = null;
        if (payload.type === 'import') {
          api = uploadFileImport;
        }
        if (payload.type === 'send') {
          api = uploadFileSend;
        }
        if (payload.type === 'tax') {
          api = uploadFileTax;
        }
        yield put({
          // 区分导入还是待发放还是待保税
          type: 'updateModelData',
          payload: {
            batchTaskType: payload.type,
          },
        });
        const response = yield call(api, payload.formData);
        if (response.success) {
          // 不是100表示需要走队列
          if (response.data && response.data.successProp !== 100) {
            const { batchId } = response.data;
            const batchTask = batchTaskFactory(batchId, namespace, 'handleBatchTask');

            yield put.resolve({
              type: `socket/${SocketActions.subSocketChannel}`,
              payload: {
                batchTask,
              },
            });
            // 订阅成功后再触发进度条
            yield put({
              type: 'updateModelData',
              payload: { showProgress: true },
            });
          } else {
            yield put({
              type: 'handleBatchTask',
              payload: response.data,
            });
          }
        } else {
          message.warning(response.message || '上传文件错误：服务器端错误');
        }

        // 无需返回response对象
      } catch (e) {
        console.error(e);
      }
    },
    { type:'throttle',ms:10000 }
  ],
    *handleBatchTask({ payload }, { put, select }) {
      const state = yield select(s => s.salaybatchcs);
      let { showProgress, resultInfo, currentStep } = state;

      const { batchQuery, batchTaskType } = state;
      showProgress = true;
      if (payload.successProp >= 100) {
        // 下载错误数据：地址
        if (batchTaskType === 'import') {
          resultInfo.errorUrl = '/csApi/wageDowoload/dowoloadErrorExist';
        } else if (batchTaskType === 'send') {
          resultInfo.errorUrl = '/csApi/wageDowoload/dowoloadErrorWage';
        } else {
          resultInfo.errorUrl = '/csApi/wageDowoload/dowoloadErrorTax';
        }
        // 下载错误数据：参数
        resultInfo.errorParams = {
          batchId: payload.batchId,
          incmType: batchQuery.incmType,
        };
        resultInfo = { ...resultInfo, ...payload };
        currentStep += 1;
        showProgress = false;
        // 先更新进度
        yield put({
          type: 'updateBatchTask',
          payload: {
            progressPercent: payload.successProp,
            resultInfo,
          },
        });
        yield delay(3000);
        // 再更新状态
        yield put({
          type: 'updateBatchTask',
          payload: {
            currentStep,
            showProgress,
          },
        });
      } else {
        yield put({
          type: 'updateBatchTask',
          payload: { progressPercent: payload.successProp, resultInfo },
        });
      }
    },
  },

  reducers: {
    // 设置修改当前state数据
    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    // 更新批量上传参数
    updateQuery(state, { payload }) {
      return {
        ...state,
        batchQuery: { ...state.batchQuery, ...payload },
      };
    },
    // 更新批量任务数据
    updateBatchTask(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
  subscriptions: {
    socket({ dispatch }) {
      service.listen(async action => {
        // 判断是否自己命名空间的回调

        if (action.namespace === namespace) {
          switch (action.type) {
            case 'task':
              await dispatch({
                type: 'handleBatchTask',
                payload: action.data,
              });
              await dispatch({
                type: `socket/${SocketActions.handleUpdateBatchTask}`,
                payload: {
                  successProp: action.data.successProp,
                  batchId: action.data.batchId,
                },
              });
              // 全局保存
              dispatch({
                type: 'publicdata/updateBatchTaskData',
                payload: action.data,
              });
              break;
          }
        }
      }, namespace);
    },
  },
};

export default ModelAddEmp;
